package kp.rpc.loadbalancer.impl;

import kp.rpc.loadbalancer.LoadBalancer;
import kp.rpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author tzf
 * @description: 轮询负载均衡器
 * @date: 2024/6/7 12:52
 */

public class RoundRobinLoadBalancer implements LoadBalancer {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if (serviceMetaInfoList == null || serviceMetaInfoList.isEmpty()) {
            return LoadBalancer.super.select(requestParams, serviceMetaInfoList);
        }
        int size = serviceMetaInfoList.size();
        if (size == 1) {
            return serviceMetaInfoList.get(0);
        }
        int index = atomicInteger.incrementAndGet() % size;
        if (atomicInteger.get() == Integer.MAX_VALUE) {
            atomicInteger.set(0);
        }
        return serviceMetaInfoList.get(index);
    }
}
